<script setup lang="js">
import {ref, onMounted} from 'vue'
import {useRoute} from 'vue-router'
import {createAdvertise, getAdvertise, updateAdvertise} from "@/api/marketingAdvertise.js";
import {Plus, ZoomIn, Download, Delete} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";

const route = useRoute()
const cardTitle = ref('')
const homeAdvertiseFrom = ref(null)
const homeAdvertise = ref({})
const defaultTypeOptions = [
  {
    label: 'PC首页轮播',
    value: 0
  },
  {
    label: 'APP首页轮播',
    value: 1
  }
];
const defaultHomeAdvertise = {
  name: null,
  type: 1,
  pic: null,
  startTime: null,
  endTime: null,
  status: 0,
  url: null,
  note: null,
  sort: 0
};
const typeOptions = Object.assign({}, defaultTypeOptions);
const rules = {
  name: [
    {required: true, message: '请输入广告名称', trigger: 'blur'},
    {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
  ],
  url: [
    {required: true, message: '请输入广告链接', trigger: 'blur'}
  ],
  startTime: [
    {required: true, message: '请选择开始时间', trigger: 'blur'}
  ],
  endTime: [
    {required: true, message: '请选择到期时间', trigger: 'blur'}
  ],
  pic: [
    {required: true, message: '请选择广告图片', trigger: 'blur'}
  ]
};
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const fileList = ref([]) // 用于存储图片文件列表

const handleRemove = (file) => {
  console.log(file)
  fileList.value = fileList.value.filter(item => item.uid !== file.uid)
}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleDownload = (file) => {
  console.log(file)
}

onMounted(() => {
  if (route.query.id) {
    cardTitle.value = '编辑广告'
    getAdvertise(route.query.id).then(res => {
      homeAdvertise.value = res.data.data
      if (homeAdvertise.value.pic) {
        fileList.value = [{name: '广告图片', url: homeAdvertise.value.pic}] // 初始化文件列表
      }
    })
  } else {
    console.log('create advertise')
    cardTitle.value = '添加广告'
    homeAdvertise.value = Object.assign({}, defaultHomeAdvertise)
    fileList.value = [];
  }
})
// 表单提交
const onSubmit = (formName) => {
  homeAdvertiseFrom.value.validate((valid) => {
    if (valid) {
      if (route.query.id) {
        updateAdvertise(route.query.id, homeAdvertise.value).then(res => {
          ElMessage.warning(res.data.message)
          console.log(homeAdvertise.value);
          console.log('广告修改成功', res.data.message);
        }).catch(err => {
          console.log('广告修改失败', err);
        })
      } else {
        createAdvertise(homeAdvertise.value).then(res => {
          ElMessage.warning(res.data.message)
          console.log(homeAdvertise.value);
          console.log('广告创建成功', res.data.message);
        }).catch(err => {
          console.log('广告创建失败', err);
        })
      }
    } else {
      ElMessage.warning('表单验证失败，请检查表单信息'); // 提供更具体的警告信息
      console.log('表单验证失败', homeAdvertiseFrom.value.errors);
    }
  });
}


// 表单重置
const resetForm = (formName) => {
  fileList.value = []
  dialogImageUrl.value = ''
  dialogVisible.value = false
  disabled.value = false
  homeAdvertise.value = ''
  ElMessage.success('表单重置成功')
}
</script>

<template>
  <div class="update-advertise">
    <el-card style="width: 40%;">
      <template #header>
        <span class="card-title">{{ cardTitle }}</span>
      </template>
      <el-form :model="homeAdvertise"
               :rules="rules"
               ref="homeAdvertiseFrom"
               label-width="150px"
               size="small">
        <el-form-item label="广告名称：" prop="name">
          <el-input v-model="homeAdvertise.name" class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="广告位置：">
          <el-select v-model="homeAdvertise.type">
            <el-option
                v-for="type in typeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间：" prop="startTime">
          <el-date-picker
              type="datetime"
              placeholder="选择日期"
              v-model="homeAdvertise.startTime"></el-date-picker>
        </el-form-item>
        <el-form-item label="到期时间：" prop="endTime">
          <el-date-picker
              type="datetime"
              placeholder="选择日期"
              v-model="homeAdvertise.endTime"></el-date-picker>
        </el-form-item>
        <el-form-item label="上线/下线：">
          <el-radio-group v-model="homeAdvertise.status">
            <el-radio :label="0">下线</el-radio>
            <el-radio :label="1">上线</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="广告图片：">
          <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :file-list="fileList"
          >
            <el-icon>
              <Plus/>
            </el-icon>

            <template #file="{ file }">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                    <el-icon><ZoomIn/></el-icon>
                  </span>
                  <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                    <el-icon><Download/></el-icon>
                  </span>
                  <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <el-icon><Delete/></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序：">
          <el-input v-model="homeAdvertise.sort" class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="广告链接：" prop="url">
          <el-input v-model="homeAdvertise.url" class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="广告备注：">
          <el-input
              class="input-width"
              type="textarea"
              :rows="5"
              placeholder="请输入内容"
              v-model="homeAdvertise.note">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('homeAdvertiseFrom')">提交</el-button>
          <el-button @click="resetForm('homeAdvertiseFrom')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image"/>
  </el-dialog>
</template>

<style scoped lang="scss">
.update-advertise {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: center;

  .card-title {
    font-size: 24px;
    font-weight: bold;
  }
}
</style>
